package org.dromara.solonplugins.bee;

import java.util.Set;

import javax.sql.DataSource;

import org.dromara.solonplugins.bee.integration.BeePropertiesManager;
import org.noear.solon.Utils;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.BeanWrap;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.VarHolder;
import org.teasoft.honey.osql.core.BeeFactory;
import org.teasoft.honey.osql.core.BeeProp;
import org.teasoft.honey.osql.core.SessionFactory;

/**
 * Solon-bee orm插件入口
 * @link https://gitee.com/automvc/bee
 * @author: xls-web (小xu中年)
 */
public class XPluginImp implements Plugin {
    @Override
    public void start(AppContext context) throws Throwable {
    	BeeProp bp = BeeProp.getBeeProp();
    	Set<String> bkeys =  bp.getKeys();
    	for(String b : bkeys) {
    		context.cfg().put(b, bp.getProp(b));
    	}
    	BeePropertiesManager bm = new BeePropertiesManager(context);
        
    	bm.getBean();//初始化和ManageConfig相关的各种bean
    	bm.xmlBean();//初始化关系型数据库操作层
    	bm.mongoXmlBean();//初始化mongodb数据库操作层
    	
    	//监听DataSource注入事件
        context.subWrapsOfType(DataSource.class, bw->{
        	//注入BeeFactory
        	BeeFactory beeFactory = BeeFactory.getInstance();
    		beeFactory.setDataSource(bw.raw());
    		context.wrapAndPut(BeeFactory.class, beeFactory);
    		
    		//注入SessionFactory
    		SessionFactory factory = new SessionFactory();
    		factory.setBeeFactory(beeFactory);
    		context.wrapAndPut(SessionFactory.class, factory);
        });
        //这里将bee.properties的配置项从solon中释放
    	for(String b : bkeys) {
    		context.cfg().remove(b);
    	}
    }
    
    private void builderAddDo(Class<?> clz, BeanWrap wrap, String annoValue) {
        if (clz.isInterface() == false) {
            return;
        }

        if (Utils.isEmpty(annoValue)) {
            wrap.context().getWrapAsync(DataSource.class, (dsBw) -> {
                create0(clz, dsBw);
            });
        } else {
            wrap.context().getWrapAsync(annoValue, (dsBw) -> {
                if (dsBw.raw() instanceof DataSource) {
                    create0(clz, dsBw);
                }
            });
        }
    }
    
    private void injectorAddDo(VarHolder varH, String annoValue) {
        if (Utils.isEmpty(annoValue)) {
            varH.context().getWrapAsync(DataSource.class, (dsBw) -> {
                inject0(varH, dsBw);
            });
        } else {
            varH.context().getWrapAsync(annoValue, (dsBw) -> {
                if (dsBw.raw() instanceof DataSource) {
                    inject0(varH, dsBw);
                }
            });
        }
    }
    
    private void create0(Class<?> clz, BeanWrap dsBw) {
       
    }

    private void inject0(VarHolder varH, BeanWrap dsBw) {
       
    }
}
